// pages/demo/demo.js
Page({
  data: {
    schema:[],
    formData: {
    },
    title: '',
    result: '',
    remark: '',
    webUrl: '',
    apiName: '',
    snapshotPath: ''
  },
  onLoad(options) {
    const that = this;
    console.log('options', options)
    wx.setNavigationBarTitle({
      title: options.title,
    })
    
    this.setData({
      title: options.title,
      zh:options.zh,
      remark: options.remark,
      webUrl: options.webUrl
    })
  },
  takeSnapshot(e) {
    // 获取 snapshot 组件实例
    this.createSelectorQuery()
      .select("#target")
      .node()
      .exec(res => {
        const node = res[0].node;
        node.takeSnapshot({
          type: 'arraybuffer',
          format: 'png',
          success: (res) => {
            console.log('快照成功', res);
            const base64 = this.arrayBufferToBase64(res.data);
            const imgSrc = 'data:image/png;base64,' + base64;
            // 设置到页面变量
            this.setData({
              snapshotPath: imgSrc,
              result: res,
              apiName: e.currentTarget.dataset.apiname
            });
            wx.showToast({ title: '快照成功', icon: 'success' });
          },
          fail: (err) => {
            console.error('快照失败', err);
            wx.showToast({ title: '快照失败', icon: 'none' });
            this.setData({
              result: err,
              apiName: e.currentTarget.dataset.apiname
            });
          }
        });
      });

  },
  arrayBufferToBase64(buffer) {
    let binary = '';
    const bytes = new Uint8Array(buffer);
    const len = bytes.byteLength;
    for (let i = 0; i < len; i++) {
      binary += String.fromCharCode(bytes[i]);
    }
    return wx.arrayBufferToBase64 ? wx.arrayBufferToBase64(buffer) : btoa(binary);
  }
});